﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BBPA.Admin.SYS.Orders.Money
{
    public partial class Form : FormPage
    {
        BLL.Orders bll = new BLL.Orders();
        Model.Orders model = new Model.Orders();
        //
        BLL.V_Orders bllV_Orders = new BLL.V_Orders();
        BLL.Orders_Goods bllOrders_Goods = new BLL.Orders_Goods();
        BLL.Goods bllGoods = new BLL.Goods();
        //
        BLL.Store bllStore = new BLL.Store();
        Model.Store modelStore = new Model.Store();
        //
        BLL.Orders_State_Log bllOrders_State_Log = new BLL.Orders_State_Log();
        BLL.V_Buyer bllV_Buyer = new BLL.V_Buyer();
        protected decimal bukuan = 0;
        protected void Page_Load(object sender, EventArgs e) { }
        /// <summary>
        /// 初始化本页Model
        /// </summary>
        public override void Page_Load_DefaultModel() { model = bll.GetModel(Master.id); modelStore = bllStore.GetModel(model.StoreID);
        bukuan = BLL.Orders.bukuan(modelStore.MasterAccount, modelStore.FrozenAccount,BLL.Orders.Get_Orders_ExpectSellPriceSum(Master.id));
        }
        /// <summary>
        /// 初始化表单
        /// </summary>
        public override void Form_Default()
        {
            if (bukuan==0)
            {
                tb_Money_helper.Visible = false;
                rbl_MoneyType.Visible = true;
                rbl_MoneyType.Items[1].Text += " 可用余额：" + StringPlus.showMoney(modelStore.MasterAccount-modelStore.FrozenAccount);
            }
            else
            {
                tb_Money_helper.Visible = true;
                lb_bukuan.Text = StringPlus.showMoney(bukuan);
                rbl_MoneyType.Visible = false;
            }
        }
        /// <summary>
        /// 绑定表单数据【修改时用】
        /// </summary>
        public override void Form_Bind()
        {
        }
        /// <summary>
        /// 提交
        /// </summary>
        public override void Form_Submit()
        {
            decimal Money = DataTypePlus.requestDecimal(tb_Money.Text);
            if (rbl_MoneyType.SelectedValue == "1" && Money == 0) { Master.ScriptManager_Alert_float("【货款金额】必须填写", false); return; }
            if (rbl_MoneyType.SelectedValue == "1")
            {//1.先充值
                if (Money > 0) model.Getmoney = Money;
                if (Master.noErr(Money < bukuan, "【收到货款】最少要是" + StringPlus.showMoney(bukuan)))
                {
                    CallBak<int> callBak_Recharge = BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, modelStore.id, EnumHelper.AccountChangeReason.Recharge, modelStore.id, Money);
                    if (!callBak_Recharge.IsSuccess) { Master.ScriptManager_Alert_float(callBak_Recharge.ErrMsg, false); return; }
                    BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Account_Change_Log, callBak_Recharge.ReturnVal, EnumHelper.OperateType.Add, "收取订单货款" + StringPlus.showMoney(Money));
                    //通知孕婴店
                    BLL.Message bllMessage = new BLL.Message();
                    bllMessage.NewMessage(0, Security.GetCurrentUserID(), modelStore.UserID,
                        "您的汇款共计" + StringPlus.showCoin(Money) + "元已收到并打入您的采购帐号，请查阅",
                        true, true);
                }
            }
            else
            {
                model.Getmoney = 0;
            }
            BBPA.BLL.Group_Good bll_group_good = new BLL.Group_Good();
            BBPA.BLL.GroupBuy bll_groupbuy = new BLL.GroupBuy();
            
            //2.再完成订单收款
            model.ExpectPriceSum = 0;//预计孕婴店采购总价
            if (model.Number.StartsWith("tg"))
            {
                BBPA.Model.GroupBuy model_groupbuy = bll_groupbuy.GetModel(model.Gbid);
                foreach (Model.Orders_Goods modelOrders_Goods in bllOrders_Goods.GetModelList("OrdersID=" + Master.id))//货品：预计价格+预计小计+实际数量初始化
                {

                    //Model.Goods modelGoods = bllGoods.GetModel(modelOrders_Goods.GoodsID);
                    //预计活动
                    DataTable dt = bll_group_good.GetList("OrdersID=" + Master.id + " and GoodsID=" + modelOrders_Goods.GoodsID).Tables[0];


                    modelOrders_Goods.ExpectDiscount = 0;// BLL.Goods.GetSellDiscount(modelOrders_Goods.GoodsID, modelOrders_Goods.ExpectAmount);
                    modelOrders_Goods.ExpectGiftNumber = 0;// BLL.Goods.GetGiftNumberSell(modelOrders_Goods.GoodsID, modelOrders_Goods.ExpectAmount);
                    //预计售价
                    modelOrders_Goods.ExpectPrice = Convert.ToDecimal(dt.Rows[0]["gggoodprice"]);//modelGoods.SellPrice;
                    modelOrders_Goods.ExpectPriceSum = Convert.ToDecimal(dt.Rows[0]["gggoodprice"]) * Convert.ToInt32(dt.Rows[0]["ExpectAmount"]);
                    model.ExpectPriceSum += modelOrders_Goods.ExpectPriceSum;
                    model.ExpectPay = model.ExpectPriceSum;

                    bllOrders_Goods.Update(modelOrders_Goods);
                }
                model_groupbuy.gbpayprice += model.ExpectPriceSum;
                bll_groupbuy.Update(model_groupbuy);
            }
            else
            {
                foreach (Model.Orders_Goods modelOrders_Goods in bllOrders_Goods.GetModelList("OrdersID=" + Master.id))//货品：预计价格+预计小计+实际数量初始化
                {

                    Model.Goods modelGoods = bllGoods.GetModel(modelOrders_Goods.GoodsID);
                    //预计活动
                    modelOrders_Goods.ExpectDiscount = BLL.Goods.GetSellDiscount(modelOrders_Goods.GoodsID, modelOrders_Goods.ExpectAmount);
                    modelOrders_Goods.ExpectGiftNumber = BLL.Goods.GetGiftNumberSell(modelOrders_Goods.GoodsID, modelOrders_Goods.ExpectAmount);
                    //预计售价
                    modelOrders_Goods.ExpectPrice = modelGoods.SellPrice;
                    modelOrders_Goods.ExpectPriceSum = BLL.Goods.GetSellPriceSum(modelOrders_Goods.GoodsID, modelOrders_Goods.ExpectAmount);//参加活动的小计
                    model.ExpectPriceSum += modelOrders_Goods.ExpectPriceSum;

                    bllOrders_Goods.Update(modelOrders_Goods);
                }
            }
            model.State = (int)EnumHelper.OrdersState.GetMoney;//修改订单状态:GetMoney
            model.FirstExpectBuyDate = bllV_Orders.GetModelList("id=" + model.id)[0].ExpectBuyDate;//首次预定采购日

            //3.冻结 预计货款
            CallBak<int> callBak_GetMoney = BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, model.StoreID, EnumHelper.AccountChangeReason.GetMoney, Master.id, model.ExpectPriceSum );
            if (!callBak_GetMoney.IsSuccess) { Master.ScriptManager_Alert_float(callBak_GetMoney.ErrMsg, false); return; }
            //4.冻结 运费
            CallBak<int> callBak_ExpectExpressMoney = BLL.Account_Change_Log.Add(EnumHelper.UserType.Store, model.StoreID, EnumHelper.AccountChangeReason.ExpectExpressMoney, Master.id, 100);
            if (!callBak_ExpectExpressMoney.IsSuccess) { Master.ScriptManager_Alert_float(callBak_ExpectExpressMoney.ErrMsg, false); return; }

            //给订单找个采购员
            List<Model.V_Buyer> listModelV_Buyer = bllV_Buyer.GetModelList("State="+(int)EnumHelper.UserState.Nomal);//队伍
            if (listModelV_Buyer.Count > 0)
            {
                int lastBuyerID = 0;
                try
                {
                    List<Model.Orders_State_Log> listModelOrders_State_Log_GetMoney = bllOrders_State_Log.GetModelList("State=" + (int)EnumHelper.OrdersState.GetMoney + " order by id desc");
                    if (listModelOrders_State_Log_GetMoney.Count > 0) lastBuyerID = bll.GetModel(listModelOrders_State_Log_GetMoney[0].OrdersID).BuyerID;
                    for (int i = 0; i < listModelV_Buyer.Count; i++)
                    {
                        if (listModelV_Buyer[i].id == lastBuyerID && i < listModelV_Buyer.Count - 1)
                        {
                            model.BuyerID = listModelV_Buyer[i + 1].id;
                            break;
                        }
                    }
                }
                catch
                {
                    lastBuyerID = listModelV_Buyer[0].id;
                }
                if (model.BuyerID == 0) model.BuyerID = listModelV_Buyer[0].id;
            }
           
            bll.Update(model);
            BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Orders, Master.id, EnumHelper.OperateType.Update, rbl_MoneyType.SelectedItem.Text+"收款，并确认预期数量和价格");
            //订单状态日志
            Model.Orders_State_Log modelOrders_State_Log = new Model.Orders_State_Log();
            modelOrders_State_Log.OrdersID = Master.id;
            modelOrders_State_Log.State = model.State;
            int Orders_State_LogID_new = bllOrders_State_Log.Add(modelOrders_State_Log);
            BLL.User_Operate_Log.Add(Security.GetCurrentUserID(), EnumHelper.TableName.Orders_State_Log, Orders_State_LogID_new, EnumHelper.OperateType.Add, rbl_MoneyType.SelectedItem.Text + "收款，并确认预期数量和价格");

            if (rbl_MoneyType.SelectedValue == "1")
            {
                
            }

            Master.SubmitOK("收款成功");
        }

        protected void rbl_MoneyType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (rbl_MoneyType.SelectedIndex == 0) group_Money.Visible = true;
            else group_Money.Visible = false;
        }
    }
}